﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace KuPeiXun.Utility
{
    /// <summary>
    /// xml操作数据访问
    /// </summary>
    /// ===============================================================
    /// 作者：邹学良 
    /// 时间：2013-03-21
    /// 描述：创建
    /// 历史：无
    /// ===============================================================
    public class XmlPathHepler
    {
        #region xml文件路径
        /// <summary>
        /// xml文件路径
        /// </summary>
        private string _xmlPath = string.Empty;
        #endregion

        #region xml文件对象
        /// <summary>
        /// xml文件对象
        /// </summary>
        private XmlDocument _xmlDoc = null;
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="xmlPath"></param>
        public XmlPathHepler(string xmlPath)
        {
            try
            {
                this._xmlPath = AppDomain.CurrentDomain.BaseDirectory + xmlPath;
                this._xmlDoc = new XmlDocument();
                this._xmlDoc.Load(this._xmlPath);
            }
            catch (Exception ex)
            {
                throw new LogHepler(ex);
            }

        }
        #endregion

        #region 通过路径获取节点的值
        /// <summary>
        /// 通过路径获取节点的值
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string GetNodeTextBySingle(string path)
        {
            try
            {
                string result = string.Empty;
                XmlNode node = this._xmlDoc.SelectSingleNode(path);
                if (node != null)
                {
                    result = node.InnerText;
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new LogHepler(ex);
            }

        }
        #endregion

        #region 通过路径和属性名获取节点其相对应的值
        /// <summary>
        /// 通过路径和属性名获取节点其相对应的值
        /// </summary>
        /// <param name="path"></param>
        /// <param name="attrName"></param>
        /// <returns></returns>
        public string GetNodeAttributeValue(string path, string attrName)
        {
            try
            {
                string result = string.Empty;
                XmlNode node = this._xmlDoc.SelectSingleNode(path);
                if (node != null)
                {
                    XmlAttribute attr = node.Attributes[attrName];
                    if (attr != null)
                    {
                        result = attr.Value.Trim();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new LogHepler(ex);
            }

        }
        #endregion
    }
}